var App =  App || {};
App.fn  = App.fn || {};

$(document).ready(function() {

  var settings  = window.libConfigs[window.libname];
  var title = settings.title || '联合图书馆';
   
   axios.defaults.baseURL = settings.api;

   $('body').addClass(window.libname);
   $('.navbar-header .title, .navbar-header .page-title').html(title);
   $('.navbar .home-link').attr('href', settings.home);

   //set token
   var timestamp = (new Date()).valueOf(); 
   axios.defaults.params = {
     'hash': getHash(timestamp, 'googleapp1'),
     'timestamp': timestamp,
     'app': 'google',
   };
   //add libcode in query
   if (settings['libcode']) {
     axios.defaults.params['lib'] = settings['libcode'];
   }
});

App.loading = function(url, callback) {
	callback();
	console.log(url);
	axios.get(url)
	  .then(function(res){
	  	callback(res);
	  })
	  .catch(function(error){
	  	console.log(error);
	  });

}

App.idashborad = function(silence) {

	  //Fullwidth line chart 1
    function line_chart1(res){

      var chartEl = $("#line-chart1");
      var data = [
        [1, 10],
        [2, 30],
        [3, 10 + 45],
        [4, 15 + 21],
        [5, 57],
        [6, 80],
        [7, 65],
        [8, 50],
        [9, 80],
        [10, 70],
        [11, 90],
        [12, 55 + 12],
        [12, 55 + 12]
      ];

      if (res && res.status == 200 && res.data.status == 1) {
      	data = [];
      	var i = 0;
      	res.data.data.data.list.forEach(function(item) {
      		var time = item.MTIME.toString();

      		var time = time.substr(0,4) + "-" + time.substr(4,2) + "-" + time.substr(6,2);
      		data.push([++i, item.TOTAL])
      	});
      	//console.log(data);
      }

      var color1 = App.color.alt3;


      //Line Chart 2

      var color1 = tinycolor( App.color.primary ).lighten( 5 ).toString();

      /**
 	    var plot_statistics = $.plot("#line-chart1", 
 				[{
	        	data: data, 
	        	showLabels: true, 
	        	label: "New Visitors", 
	        	labelPlacement: "below", 
	        	canvasRender: true, 
	        	cColor: "#FFFFFF" 
      			}
      	], {
        series: {
          lines: {
            show: true,
            lineWidth: 2, 
            fill: true,
            fillColor: { colors: [{ opacity: 0.6 }, { opacity: 0.6}] }
          },
          fillColor: "rgba(0, 0, 0, 1)",
          points: {
            show: true,
            fill: true,
            fillColor: color1
          },
          shadowSize: 0
        },
        legend:{
          show: false
        },
        grid: {
          show:true,
          margin: {
          	left: -8,
          	right: -8,
          	top: 0,
          	botttom: 0
          },
          labelMargin: 0,
          axisMargin: 0,
          hoverable: true,
          clickable: true,
          tickColor: "rgba(0, 0, 0, 0)",
          borderWidth: 0
        },
        colors: [color1,"#1fb594"],
        xaxis: {
          autoscaleMargin: 0,
          mode: "time",
    	  timeformat: "%Y%m%d"
        },
        yaxis: {
          autoscaleMargin: 0.5,
          ticks: 5,
          tickDecimals: 0
        }
      });

    **/

	

	 var line_chart001 = $.plot($("#line-chart1"), [{
        data: data,
        label: "Sales"
      }
      ], {
        series: {
          lines: {
            show: true,
            lineWidth: 2, 
            fill: true,
            fillColor: {
              colors: [{
                opacity: 0.25
              }, {
                opacity: 0.25
              }
              ]
            } 
          },
          points: {
            show: true
          },
          shadowSize: 2
        },
        legend:{
          show: false
        },
        grid: {
          labelMargin: 10,
          axisMargin: 500,
          hoverable: true,
          clickable: true,
          tickColor: "rgba(0,0,0,0.15)",
          borderWidth: 0
        },
        colors: ["#50ACFE", "#4A8CF7", "#52e136"],
        xaxis: {
          ticks: 11,
          tickDecimals: 0,
          mode: "time",
    	  timeformat: "%Y-%m-%d"
        },
        yaxis: {
          ticks: 5,
          tickDecimals: 0
        }
      });


    }


     //Top pie widget 3
    App.fn.widget_top_gender = function(res){
	    
	    var data = [
	    	{ label: "男", data: 70 },
	    	{ label: "女", data: 30 }
	    ];

	    if (res && res.data.status == 1) {
	    	data = [];
	    	//console.log(res.data);
        total = 0;
        var result = res.data.data.data;
        result['M'] = 0;
        result['F'] = 0; 
        result['U'] = 0;
	    	result.forEach(function (item) {
	    		if (item.SEX == 'MALE' || item.SEX == '1' || item.SEX == '男') {
            result['M'] += item.TOTAL;
	    		}
	    		else if (item.SEX == 'FEMALE' || item.SEX == '0' || item.SEX == '女') {
            result['F'] += item.TOTAL;
	    		}
	    		else {
	    			result['U'] += item.TOTAL;
          }           
	    		total += item.TOTAL;
        });
        data.push({label: "男", data: result['M']});
        $("#spk3 .number").html(result['M']);

        data.push({label: "女", data: result['F']});
        $("#spk2 .number").html(result['F']);

        data.push({label: "未知", data: result['U']});
	    	$("#spk1 .number").html(result['U']);
	    }

     	var color1 = App.color.alt3;
      var color2 = tinycolor( App.color.alt1 ).lighten( 7.5 ).toString();
      var color3 = App.color.alt2;

      var legendContainer = $("#widget-top-gender").parent().next().find(".legend");
	    $.plot('#widget-top-gender', data, {
		    series: {
					pie: {
						show: true,
						label: {
							show: false
						},
						highlight: {
							opacity: 0.1
						}
		      }
		    },
		    grid:{
		    	hoverable: true
		    },
		    legend:{
		    	show: true,
		    	container: legendContainer
		    },
		    colors: [color1, color2, color3]
			});
    }



    App.fn.radar_chart = function(res){

     /**
		   * Randomize array element order in-place.
		   * Using Durstenfeld shuffle algorithm.
		   */
		  function shuffleArray(array) {
		    for (var i = array.length - 1; i > 0; i--) {
		        var j = Math.floor(Math.random() * (i + 1));
		        var temp = array[i];
		        array[i] = array[j];
		        array[j] = temp;
		    }
		    return array;
		  }

      var color1 = tinycolor( App.color.primary ).lighten( 6 );
      var color2 = tinycolor( App.color.alt4 ).lighten( 6.5 );

      var data = {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [
          /**{
            label: "My First dataset",
            fillColor: color2.setAlpha(.5).toString(),
            pointColor: color2.setAlpha(.8).toString(),
            strokeColor: color2.setAlpha(.8).toString(),
            highlightFill: color2.setAlpha(.75).toString(),
            highlightStroke: color2.toString(),
            data: [65, 59, 80, 81, 56, 55, 40]
          }
          ,**/
           {
            label: "My Second dataset",
            fillColor: color1.setAlpha(.5).toString(),
            pointColor: color1.setAlpha(.8).toString(),
            strokeColor: color1.setAlpha(.8).toString(),
            highlightFill: color1.setAlpha(.75).toString(),
            highlightStroke: color1.toString(),
            data: [28, 48, 40, 19, 86, 27, 90]
          }
        ]
      };

      if (res && res.data.status == 1) {
      	data.labels = [];
      	data.datasets[0].data = [];
      	var i = 0;
      	var dataset = {};
      	var items = res.data.data.data.slice(1, 10);
      	var items = shuffleArray(items);
      	items.forEach(function(item) {
      		//if (item.CAT == 'I') return;
      		data.labels.push(item.CAT_NAME);
      		data.datasets[0].data.push(item.TOTAL);
      	});
        //因为第一个分类太多，跟其他没法对比，单独拿出来
      	var top = res.data.data.data[0];
        console.log(top);
      	$('#user-radar-n1 .number').html(top.CAT_NAME + ':' + top.TOTAL);
      	$('#user-radar-n2 .number').html(res.data.detail);
      }

      var radarChart = new Chart( $("#user-radar-chart1").get(0).getContext("2d") ).Radar(data, {
        scaleShowLine : true,
        responsive: true,
        maintainAspectRatio: false,
        legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
      });
    }


    //Counter
    App.fn.counter = function (res, random){
      //console.log("counter" , res);
      if (res.data.status == 1) {
        //更新流通图的数字
        if ($('#top-data-circulate').size() > 0) {
          $('#top-data-circulate').html(res.data.data.CIRCULATES);
        }

      	for(var i in res.data.data) {
      		var el = $('#data-'+i.toLowerCase());
      		//console.log(i + ':' + res.data.data[i]);
      		if (el.size() && res.data.data[i] > 0) {
      			$('.value', el).data('end', res.data.data[i]);
      		}
      	}
      }

      $('[data-toggle="counter"]').each(function(i, e){
        //counter randomly
        var rand = Math.random() * 5;
        if (random && rand > 2) {
          return true;
        }

        var _el       = $(this);
        var prefix    = '';
        var suffix    = '';
        var start     = 0;
        var end       = 0;
        var decimals  = 0;
        var duration  = 2.5;

        if( _el.data('prefix') ){ prefix = _el.data('prefix'); }

        if( _el.data('suffix') ){ suffix = _el.data('suffix'); }

        if( _el.data('start') ){ start = _el.data('start'); }

        if( _el.data('end') ){ end = _el.data('end'); }

        if( _el.data('decimals') ){ decimals = _el.data('decimals'); }

        if( _el.data('duration') ){ duration = _el.data('duration'); }

        var count = new CountUp(_el.get(0), start, end, decimals, duration, { 
          suffix: suffix,
          prefix: prefix,
        });

        count.start();
      });
    }

  App.fn.widget_pie_holding= function(res){

    var data =  [
        { label: "Premium Purchases", data: 15 },
        { label: "Standard Plans", data: 55 },
        { label: "Services", data: 30 }
    ];

      //ajax
      if (res && res.status == 200 && res.data.status == 1) {
        data = [];
        var total = parseInt(res.data.detail);
        total = total > 1 ? total : 10000;

        var num = 0;
        var all = 0;
        res.data.data.data.forEach(function(v) {
          if (++num>6)  return;
          all += v.TOTAL;
          data.push({label: v.CAT_NAME, data: (v.TOTAL*100/total) });
        });
        data.push({label: '其他', data: 100*(total-all)/total});
      }
      

      var color1 = tinycolor( App.color.primary ).lighten( 5 ).toString();
      var color2 = App.color.alt2;
      var color3 = App.color.alt1;

      var legendContainer = $("#widget-top-hold").parent().next().find(".legend");

      var labelFormatter = function(label, series) {
        return "<div style='font-size:8pt; text-align:center; padding:2px; color:white;'>" + label.substr(0,2) + "<br/>" + Math.round(series.percent) + "%</div>";
      }

      $.plot('#widget-top-hold', data, {
        series: {
          pie: {
            show: true,
            innerRadius: 0.27,
            highlight: {
              opacity: 0.1
            },
            label: {
              show: true,
                radius: 0.8,
                formatter: labelFormatter,
                background: {
                    opacity: 0.4,
                    color: '#000'
                }
            }
          }
        },
        grid:{
          hoverable: true,
          clickable: true
        },
        legend:{
          container: legendContainer
        },
          colors: [ color1, color2, color3]  
      });
    };


    var update_summary = function() {
      axios.get('stat/summary').then(function(res) {
        var data = res.data.data;
        var el = $('#summary-info');
        var html = '';
        if (data.READERS) {
          $('.title', el).html("读者数量");
          $('.number', el).html(data.READERS);
          html += el.html();
        }

        if (data.HOLDINGS) {
          $('.title', el).html("馆藏数量");
          $('.number', el).html(data.HOLDINGS);
          html += el.html();
        }

        if (data.BOOKINGS) {
          $('.title', el).html("预约数量");
          $('.number', el).html(data.BOOKINGS);
          html += el.html();
        }

        if (data.LIBS) {
          $('.title', el).html("成员馆");
          $('.number', el).html(data.LIBS);
          html += el.html();
        }
        el.html(html);
      });
  }

    //Init
    if (silence) {
      return; //don't initialize
    }

    update_summary();

    App.loading('stat/circulates4day?size=30', function(res) {
    	//console.log(res);
      try {
		    line_chart1(res);
      } 
      catch(e) {};
		  //update_holding_list(res);
	  });

    App.loading('stat/holdings', function(res) {
      App.fn.widget_pie_holding(res);
    });

	  App.loading('stat/readers', App.fn.widget_top_gender);

	  //调用两次会多画一张图
	  axios.get('stat/personas').then(App.fn.radar_chart);
    //line_chart1();
    //widget_pie_holding();
    axios.get('stat/summary').then(App.fn.counter);
  
}

function truncate(str, len){
  if(str.length > len){
    return str.substr(0, len) + '...';
  } else {
    return str;
  }
}
function getCover(isbn) {
  return window.coverURL + isbn;
}
function showName(name) {
  return name.substr(0,1) + '*' + name.substr(2);
}
function getHash(timestamp, key) {
  if (!key) {
     key = 'fstest20170707';
  }
  return hash3(timestamp + key);
}
